package com.aptech.controller;

import com.aptech.entity.RealEstate;
import com.aptech.controller.util.JsfUtil;
import com.aptech.controller.util.PaginationHelper;
import java.util.List;
import com.aptech.session.RealEstateFacadeLocal;
import java.io.FileOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import org.apache.myfaces.custom.fileupload.UploadedFile;

@ManagedBean(name = "realEstateController")
@SessionScoped
public class RealEstateController implements Serializable {

    @EJB
    private RealEstateFacadeLocal realEstateFacade;
    private RealEstate current;
    private DataModel items = null;
    private DataModel items1 = null;
    private DataModel items2 = null;
    private DataModel items3 = null;
    private PaginationHelper pagination;
    private PaginationHelper pagination1;
    private PaginationHelper pagination2;
    private PaginationHelper pagination3;
    private int selectedItemIndex;
    int pageSize = 10;
    int pageSize1 = 5;

    private UploadedFile uploadedFile;

    public UploadedFile getUploadedFile() {
        return uploadedFile;
    }

    public void setUploadedFile(UploadedFile uploadedFile) {
        this.uploadedFile = uploadedFile;
    }
    public int getBathrooms() {
        return bathrooms;
    }

    public void setBathrooms(int bathrooms) {
        this.bathrooms = bathrooms;
    }

    public int getHouseTypeID() {
        return houseTypeID;
    }

    public void setHouseTypeID(int houseTypeID) {
        this.houseTypeID = houseTypeID;
    }
    private int bathrooms;
    private int houseTypeID;

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    public DataModel getItems1() {
        if (items1 == null) {
            items1 = getPagination1().createPageDataModel();
        }
        return items1;
    }

    public DataModel getItems2() {
        if (items2 == null) {
            items2 = getPagination2().createPageDataModel();
        }
        return items2;
    }

    public DataModel getItems3() {
        if (items3 == null) {
            items3 = getPagination3().createPageDataModel();
        }
        return items3;
    }

    public RealEstateController() {
    }

    public RealEstate getSelected() {
        if (current == null) {
            current = new RealEstate();
            selectedItemIndex = -1;
        }
        return current;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(pageSize) {

                @Override
                public int getItemsCount() {
                    return realEstateFacade.count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(realEstateFacade.findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public PaginationHelper getPagination1() {
        if (pagination1 == null) {
            pagination1 = new PaginationHelper(pageSize1) {

                @Override
                public int getItemsCount() {
                    return realEstateFacade.selectByType("House for rent").size();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(selectByType1(getPageFirstItem(), getPageFirstItem() + getPageSize()));
                }
            };
        }
        return pagination1;
    }

    public PaginationHelper getPagination2() {
        if (pagination2 == null) {
            pagination2 = new PaginationHelper(pageSize1) {

                @Override
                public int getItemsCount() {
                    return realEstateFacade.selectByType("Selling house").size();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(selectByType2(getPageFirstItem(), getPageFirstItem() + getPageSize()));
                }
            };
        }
        return pagination2;
    }

    public PaginationHelper getPagination3() {
        if (pagination3 == null) {
            pagination3 = new PaginationHelper(pageSize1) {

                @Override
                public int getItemsCount() {
                    return realEstateFacade.selectByType("Guest house").size();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(selectByType3(getPageFirstItem(), getPageFirstItem() + getPageSize()));
                }
            };
        }
        return pagination3;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (RealEstate) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareView1() {
        current = (RealEstate) getItems1().getRowData();
        selectedItemIndex = pagination1.getPageFirstItem() + getItems1().getRowIndex();
        return "DetailsHouseForRent";
    }

    public String prepareView2() {
        current = (RealEstate) getItems2().getRowData();
        selectedItemIndex = pagination2.getPageFirstItem() + getItems2().getRowIndex();
        return "DetailsHouseSelling";
    }

    public String prepareView3() {
        current = (RealEstate) getItems3().getRowData();
        selectedItemIndex = pagination3.getPageFirstItem() + getItems3().getRowIndex();
        return "DetailsGuestHouse";
    }

    public String prepareCreate() {
        current = new RealEstate();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            String fileName = uploadedFile.getName();
            String contentType = uploadedFile.getContentType();
            byte[] bytes = uploadedFile.getBytes();

            // save to upload directory
            String path = FacesContext.getCurrentInstance().getExternalContext().getRealPath("resources");
            FileOutputStream fos = new FileOutputStream(path + "/" + fileName);
            fos.write(bytes);
            fos.close();
            System.out.println("file saved to upload dir");
            
            // save news
            if (uploadedFile != null) {
                current.setImageURL(uploadedFile.getName());
            } else {
                current.setImageURL("Not available");
            }
            realEstateFacade.create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("RealEstateCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (RealEstate) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            realEstateFacade.edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("RealEstateUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (RealEstate) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            realEstateFacade.remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("RealEstateDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = realEstateFacade.count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = realEstateFacade.findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    private void recreateModel() {
        items = null;
        items1 = null;
        items2 = null;
        items3 = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String next1() {
        getPagination1().nextPage();
        recreateModel();
        return "houseForRent";
    }

    public String next2() {
        getPagination2().nextPage();
        recreateModel();
        return "houseSelling";
    }

    public String next3() {
        getPagination3().nextPage();
        recreateModel();
        return "guestHouse";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public String previous1() {
        getPagination1().previousPage();
        recreateModel();
        return "houseForRent";
    }

    public String previous2() {
        getPagination2().previousPage();
        recreateModel();
        return "houseSelling";
    }

    public String previous3() {
        getPagination3().previousPage();
        recreateModel();
        return "guestHouse";
    }

    public String viewPage(int page) {
        getPagination().viewPage(page);
        recreateModel();
        return "List";
    }

    public String viewPage1(int page) {
        getPagination1().viewPage(page);
        recreateModel();
        return "houseForRent";
    }

    public String viewPage2(int page) {
        getPagination2().viewPage(page);
        recreateModel();
        return "houseSelling";
    }

    public String viewPage3(int page) {
        getPagination3().viewPage(page);
        recreateModel();
        return "guestHouse";
    }

    public int totalPage() {
        return realEstateFacade.count() % pageSize == 0 ? realEstateFacade.count() / pageSize : realEstateFacade.count() / pageSize + 1;
    }

    public int totalPage1() {
        int size = realEstateFacade.selectByType("House for rent").size();
        return size % pageSize1 == 0 ? size / pageSize1 : size / pageSize1 + 1;
    }

    public int totalPage2() {
        int size = realEstateFacade.selectByType("Selling house").size();
        return size % pageSize1 == 0 ? size / pageSize1 : size / pageSize1 + 1;
    }

    public int totalPage3() {
        int size = realEstateFacade.selectByType("Guest house").size();
        return size % pageSize1 == 0 ? size / pageSize1 : size / pageSize1 + 1;
    }

    public List<RealEstate> selectTop1() {
        return realEstateFacade.selectTop("House for rent");
    }

    public List<RealEstate> selectTop2() {
        return realEstateFacade.selectTop("Selling house");
    }

    public List<RealEstate> selectTop3() {
        return realEstateFacade.selectTop("Guest house");
    }

    public RealEstate getDetails() {
        return current;
    }

    public String showDetail(RealEstate current) {
        this.current = current;
        return "Detail";
    }

    public List<RealEstate> selectByType1(int from, int to) {
        List<RealEstate> list = realEstateFacade.selectByType("House for rent");
        List<RealEstate> listsub = new ArrayList<RealEstate>();
        for (int i = 0; i < list.size(); i++) {
            if (i >= from && i < to) {
                listsub.add(list.get(i));
            }
        }
        return listsub;
    }

    public List<RealEstate> selectByType2(int from, int to) {
        List<RealEstate> list = realEstateFacade.selectByType("Selling house");
        List<RealEstate> listsub = new ArrayList<RealEstate>();
        for (int i = 0; i < list.size(); i++) {
            if (i >= from && i < to) {
                listsub.add(list.get(i));
            }
        }
        return listsub;
    }

    public List<RealEstate> selectByType3(int from, int to) {
        List<RealEstate> list = realEstateFacade.selectByType("Guest house");
        List<RealEstate> listsub = new ArrayList<RealEstate>();
        for (int i = 0; i < list.size(); i++) {
            if (i >= from && i < to) {
                listsub.add(list.get(i));
            }
        }
        return listsub;
    }
    //Search House 

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(realEstateFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(realEstateFacade.findAll(), true);


    }

    @FacesConverter(forClass = RealEstate.class)
    public static class RealEstateControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            RealEstateController controller = (RealEstateController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "realEstateController");
            return controller.realEstateFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof RealEstate) {
                RealEstate o = (RealEstate) object;
                return getStringKey(o.getRealEstateID());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + RealEstateController.class.getName());
            }
        }
    }
}
